package com.hk.core.authentication.api.validatecode;

import com.hk.commons.util.JsonUtils;
import org.springframework.data.redis.connection.RedisConnectionFactory;

import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * @author kevin
 * @date 2019-9-3 16:17
 */
public record RedisCacheValidateCodeStrategy<C extends ValidateCode>(
        RedisConnectionFactory redisConnectionFactory) implements ValidateCodeStrategy<C> {

    @Override
    public void save(C validateCode) {
        try (var connection = redisConnectionFactory.getConnection()) {
            connection.stringCommands().setEx(validateCode.getId().getBytes(StandardCharsets.UTF_8), validateCode.getExpireSecond(),
                    JsonUtils.serialize(validateCode).getBytes(StandardCharsets.UTF_8));
        }
    }

    @Override
    public C get(C validateCode, Class<C> clazz) {
        try (var connection = redisConnectionFactory.getConnection()) {
            var values = connection.stringCommands().get(validateCode.getId().getBytes(StandardCharsets.UTF_8));
            if (Objects.isNull(values)) {
                return null;
            }
            var str = new String(values, StandardCharsets.UTF_8);
            if (String.class.isAssignableFrom(clazz)) {
                return clazz.cast(str);
            }
            return JsonUtils.deserialize(str, clazz);
        }
    }

    @Override
    public void remove(C validateCode) {
        try (var connection = redisConnectionFactory.getConnection()) {
            connection.keyCommands().del(validateCode.getId().getBytes(StandardCharsets.UTF_8));
        }
    }
}
